<route lang="jsonc">{
  "style": {
    "navigationBarTitleText": "公司审核"
  }
}</route>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'
import { corporateAuth, corporateAuthInfo, delCorporateAuth, salesCompany } from '@/api/user'
import ImageUpload from '@/components/ImageUpload.vue'

const authInfo = ref(null)
const submitting = ref(false)
const salesCompanyList = ref([])
const filteredSalesCompanyList = ref([])
const showSalesCompanyPicker = ref(false)
const salesCompanySearchText = ref('')
const form = reactive({
  legal_name: '',
  legal_telephone: '',
  license_photo: '',
  bank_no: '',
  bank_user: '',
  bank_name: '',
  bank_branch: '',
  bank_addr: '',
  company_id: '', // 新增销售公司ID字段
  sales_company_name: '', // 新增销售公司名称字段（用于显示）
})

onLoad(async () => {
  getSalesCompany()
  await loadAuthInfo()
})

function getSalesCompany() {
  salesCompany({ is_sale: 1, size: 999 }).then(res => {
    console.log(res, '7777');
    salesCompanyList.value = res.data.items.filter(item => item.status === 1) || []
    filteredSalesCompanyList.value = salesCompanyList.value
  })
}

// 筛选销售公司
function filterSalesCompany() {
  if (!salesCompanySearchText.value.trim()) {
    filteredSalesCompanyList.value = salesCompanyList.value
  } else {
    const searchText = salesCompanySearchText.value.toLowerCase()
    filteredSalesCompanyList.value = salesCompanyList.value.filter(item =>
      item.name.toLowerCase().includes(searchText) ||
      item.cityName.toLowerCase().includes(searchText) ||
      item.ownerName.toLowerCase().includes(searchText)
    )
  }
}

// 选择销售公司
function selectSalesCompany(company) {
  const { ownerName, ownerTel, creditAccount, creditName } = company
  form.legal_name = ownerName
  form.legal_telephone = ownerTel
  form.bank_no = creditAccount
  form.bank_user = creditName
  form.company_id = company.id
  form.sales_company_name = company.name
  showSalesCompanyPicker.value = false
  salesCompanySearchText.value = ''
  filteredSalesCompanyList.value = salesCompanyList.value
}

// 打开销售公司选择器
function openSalesCompanyPicker() {
  showSalesCompanyPicker.value = true
  filteredSalesCompanyList.value = salesCompanyList.value
}

// 关闭销售公司选择器
function closeSalesCompanyPicker() {
  showSalesCompanyPicker.value = false
  salesCompanySearchText.value = ''
  filteredSalesCompanyList.value = salesCompanyList.value
}

// 加载企业认证信息
async function loadAuthInfo() {
  try {
    const res = await corporateAuthInfo()
    if (res) {
      authInfo.value = res
      // 将已有信息填充到表单中
      Object.assign(form, {
        legal_name: res.legal_name || '',
        legal_telephone: res.legal_telephone || '',
        license_photo: res.license_photo || '',
        bank_no: res.bank_no || '',
        bank_user: res.bank_user || '',
        bank_name: res.bank_name || '',
        bank_branch: res.bank_branch || '',
        bank_addr: res.bank_addr || '',
        company_id: res.company_id || '',
        sales_company_name: res.sales_company_name || '',
      })
    }
  }
  catch (error) {
    console.log('获取认证信息失败:', error)
    // 如果是404或者没有认证信息，不显示错误
    if (error?.statusCode !== 404) {
      uni.showToast({
        title: '获取认证信息失败',
        icon: 'none',
      })
    }
  }
}

// 删除企业认证信息
async function handleDelete() {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除当前的企业认证信息吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await delCorporateAuth(authInfo.value.id)
          uni.showToast({
            title: '删除成功',
            icon: 'success',
          })
          // 清空数据
          authInfo.value = null
          Object.assign(form, {
            legal_name: '',
            legal_telephone: '',
            license_photo: '',
            bank_no: '',
            bank_user: '',
            bank_name: '',
            bank_branch: '',
            bank_addr: '',
          })
        }
        catch (error) {
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none',
          })
        }
      }
    },
  })
}

// 提交企业认证
async function handleSubmit() {
  const requiredFields: { key: keyof typeof form, label: string }[] = [
    { key: 'company_id', label: '请选择公司' },
    // { key: 'legal_name', label: '负责人姓名' },
    // { key: 'legal_telephone', label: '负责人电话' },
    // { key: 'license_photo', label: '经营执照照片' },
    // { key: 'bank_no', label: '账户' },
    // { key: 'bank_user', label: '账户名' },
    // { key: 'bank_name', label: '对公账户开户银行' },
    // { key: 'bank_branch', label: '对公账户开户支行' },
    // { key: 'bank_addr', label: '对公账户开户银行地址' },
  ]

  for (const field of requiredFields) {
    if (!form[field.key]) {
      uni.showToast({
        title: `请输入${field.label}`,
        icon: 'none',
      })
      return
    }
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(form.legal_telephone)) {
    uni.showToast({
      title: '请输入正确的手机号码',
      icon: 'none',
    })
    return
  }

  submitting.value = true
  try {
    await corporateAuth(form)
    uni.showToast({
      title: '提交成功，请等待审核',
      icon: 'success',
    })

    // 提交成功后重新加载认证信息
    setTimeout(async () => {
      await loadAuthInfo()
    }, 1500)
  }
  // catch (error) {
  //   uni.showToast({
  //     title: '提交失败，请重试',
  //     icon: 'none',
  //   })
  // }
  finally {
    submitting.value = false
  }
}

// 预览图片
function previewImage(url: string) {
  uni.previewImage({
    urls: [url],
    current: url,
  })
}
</script>

<template>
  <view class="container">
    <!-- 已有认证信息展示 -->
    <view v-if="authInfo" class="auth-info-wrapper">
      <view class="auth-header">
        <text class="auth-title">当前认证信息</text>
        <wd-button size="small" type="error" @click="handleDelete">
          删除认证
        </wd-button>
      </view>
      <view class="auth-content">
        <view class="info-item">
          <text class="info-label">销售公司：</text>
          <text class="info-value">{{ authInfo.company_name || '未选择' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">负责人姓名：</text>
          <text class="info-value">{{ authInfo.legal_name }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">负责人电话：</text>
          <text class="info-value">{{ authInfo.legal_telephone }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">账户：</text>
          <text class="info-value">{{ authInfo.bank_no }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">账户名：</text>
          <text class="info-value">{{ authInfo.bank_user }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">开户银行：</text>
          <text class="info-value">{{ authInfo.bank_name }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">开户支行：</text>
          <text class="info-value">{{ authInfo.bank_branch }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">银行地址：</text>
          <text class="info-value">{{ authInfo.bank_addr }}</text>
        </view>
        <view class="info-item photo-item">
          <text class="info-label">经营证照照片：</text>
          <view class="photo-wrapper">
            <image v-if="authInfo.license_photo" :src="authInfo.license_photo" class="license-photo" mode="aspectFit"
              @click="previewImage(authInfo.license_photo)" />
            <text v-else class="no-photo">暂无照片</text>
          </view>
        </view>
      </view>
    </view>

    <view v-else class="form-wrapper">
      <view class="form-title">
        {{ '企业认证申请' }}
      </view>

      <view class="form-item">
        <view class="label">
          销售公司
        </view>
        <view class="input-wrapper picker-wrapper" @click="openSalesCompanyPicker">
          <text class="picker-value" :class="{ placeholder: !form.sales_company_name }">
            {{ form.sales_company_name || '请选择销售公司' }}
          </text>
          <uni-icons :type="'down' as any" size="16" color="#c0c4cc"></uni-icons>
        </view>
      </view>

      <view class="form-item">
        <view class="label">
          负责人姓名
        </view>
        <view class="input-wrapper disabled-input">
          <wd-input disabled v-model="form.legal_name" placeholder-style="color: #c0c4cc" no-border
            placeholder="请输入负责人姓名" />
        </view>
      </view>

      <view class="form-item">
        <view class="label">
          负责人电话
        </view>
        <view class="input-wrapper disabled-input">
          <wd-input disabled v-model="form.legal_telephone" type="number" placeholder-style="color: #c0c4cc" no-border
            placeholder="请输入负责人电话" />
        </view>
      </view>
      <view class="form-item">
        <view class="label">
          账户
        </view>
        <view class="input-wrapper disabled-input">
          <wd-input disabled v-model="form.bank_no" type="number" placeholder-style="color: #c0c4cc" no-border
            placeholder="请输入账户" />
        </view>
      </view>

      <view class="form-item">
        <view class="label">
          账户名
        </view>
        <view class="input-wrapper disabled-input">
          <wd-input disabled v-model="form.bank_user" placeholder-style="color: #c0c4cc" no-border
            placeholder="请输入账户名" />
        </view>
      </view>
      <view class="form-item">
        <view class="label">
          对公账户开户银行
        </view>
        <view class="input-wrapper">
          <wd-input v-model="form.bank_name" placeholder-style="color: #c0c4cc" no-border placeholder="请输入对公账户开户银行" />
        </view>
      </view>

      <view class="form-item">
        <view class="label">
          对公账户开户支行
        </view>
        <view class="input-wrapper">
          <wd-input v-model="form.bank_branch" placeholder-style="color: #c0c4cc" no-border placeholder="请输入对公账户开户支行" />
        </view>
      </view>

      <view class="form-item">
        <view class="label">
          对公账户开户银行地址
        </view>
        <view class="input-wrapper">
          <wd-input v-model="form.bank_addr" placeholder-style="color: #c0c4cc" no-border placeholder="请输入对公账户开户银行地址" />
        </view>
      </view>

      <view class="form-item">
        <view class="label">
          经营执照照片
        </view>
        <view class="upload-wrapper">
          <ImageUpload v-model="form.license_photo" :max-count="1" accept="image/*" placeholder="请上传经营执照照片" />
        </view>
      </view>
    </view>

    <view v-if="!authInfo" class="submit-button-wrapper">
      <wd-button block custom-class="submit-button" :loading="submitting" @click="handleSubmit">
        {{ submitting ? '提交中...' : '提交审核' }}
      </wd-button>
    </view>

    <!-- 销售公司选择器弹窗 -->
    <wd-popup v-model="showSalesCompanyPicker" position="bottom" custom-style="height: 70vh;">
      <view class="sales-company-picker">
        <view class="picker-header">
          <text class="picker-title">选择销售公司</text>
          <text class="picker-close" @click="closeSalesCompanyPicker">×</text>
        </view>

        <view class="search-wrapper">
          <wd-input v-model="salesCompanySearchText" placeholder="搜索公司名称、城市或负责人" @input="filterSalesCompany"
            clearable />
        </view>

        <scroll-view class="company-list" scroll-y>
          <view v-for="company in filteredSalesCompanyList" :key="company.id" class="company-item"
            :class="{ selected: form.company_id === company.id }" @click="selectSalesCompany(company)">
            <view class="company-info">
              <text class="company-name">{{ company.name }}</text>
              <text class="company-detail">{{ company.cityName }}-{{ company.ownerName }}-{{ company.ownerTel }}</text>
              <!-- <text class="company-phone">{{ company.ownerTel }}</text> -->
            </view>
            <text v-if="form.company_id === company.id" class="selected-icon">✓</text>
          </view>

          <view v-if="filteredSalesCompanyList.length === 0" class="no-data">
            <text>暂无匹配的销售公司</text>
          </view>
        </scroll-view>
      </view>
    </wd-popup>

  </view>
</template>

<style lang="scss" scoped>
.container {
  background-color: #fcf8f1;
  min-height: 100vh;
  padding: 1rem;
}

.auth-info-wrapper {
  background-color: white;
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;

  .auth-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid #f0f0f0;

    .auth-title {
      font-size: 1rem;
      font-weight: bold;
      color: #333;
    }
  }

  .auth-content {
    .info-item {
      display: flex;
      margin-bottom: 0.5rem;

      .info-label {
        width: 120px;
        color: #666;
        font-size: 0.875rem;
      }

      .info-value {
        flex: 1;
        color: #333;
        font-size: 0.875rem;
      }

      &.photo-item {
        align-items: flex-start;

        .photo-wrapper {
          flex: 1;

          .license-photo {
            width: 120px;
            height: 80px;
            border-radius: 4px;
            border: 1px solid #e0e0e0;
            cursor: pointer;
          }

          .no-photo {
            color: #999;
            font-size: 0.875rem;
            font-style: italic;
          }
        }
      }
    }
  }
}

.form-wrapper {
  background-color: white;
  padding: 1rem;
  border-radius: 8px;

  .form-title {
    font-size: 1rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 1rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid #f0f0f0;
  }
}

.form-item {
  margin-bottom: 1rem;

  .label {
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
    color: #333;
    font-weight: 500;
  }

  .disabled-input {
    :deep(.wd-input) {
      color: #000000 !important;

      input {
        color: #000000 !important;
      }

      .wd-input__inner {
        color: #000000 !important;
      }
    }
  }

  .input-wrapper {
    border: 1px dashed #e0e0e0;
    border-radius: 4px;
    padding: 0 0.75rem;
    height: 44px;
    display: flex;
    align-items: center;
  }

  .upload-wrapper {
    border: 1px dashed #e0e0e0;
    border-radius: 4px;
    padding: 0.75rem;
    min-height: 100px;
  }

  .picker-value {
    font-weight: bold;
    font-size: 14px;
    width: 100%;

    &.placeholder {
      color: #c0c4cc;
    }
  }
}

.submit-button-wrapper {
  margin-top: 2rem;
}

:deep(.submit-button) {
  background-color: #ff770d !important;
  border-color: #ff770d !important;
  color: #ffffff !important;
  font-weight: bold;
  font-size: 30rpx !important;
  border-radius: 9999px !important;
  height: 44px !important;
}

:deep(.wd-input) {
  width: 100%;
  --wd-input-font-size: 14px;
}

.picker-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;

  .picker-arrow {
    color: #c0c4cc;
    font-size: 16px;
    transform: rotate(90deg);
  }
}

.sales-company-picker {
  height: 100%;
  display: flex;
  flex-direction: column;

  .picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    border-bottom: 1px solid #f0f0f0;

    .picker-title {
      font-size: 1rem;
      font-weight: bold;
      color: #333;
    }

    .picker-close {
      font-size: 1.5rem;
      color: #999;
      cursor: pointer;
    }
  }

  .search-wrapper {
    padding: 1rem;
    border-bottom: 1px solid #f0f0f0;
  }

  .company-list {
    flex: 1;
    padding: 0 1rem;

    .company-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 1rem 0;
      border-bottom: 1px solid #f5f5f5;
      cursor: pointer;

      &.selected {
        background-color: #fff7e6;
      }

      .company-info {
        flex: 1;

        .company-name {
          display: block;
          font-size: 1rem;
          font-weight: 500;
          color: #333;
          margin-bottom: 0.25rem;
        }

        .company-detail {
          display: block;
          font-size: 0.875rem;
          color: #666;
          margin-bottom: 0.25rem;
        }

        .company-phone {
          display: block;
          font-size: 0.875rem;
          color: #999;
        }
      }

      .selected-icon {
        color: #ff770d;
        font-size: 1.25rem;
        font-weight: bold;
      }
    }

    .no-data {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
      color: #999;
    }
  }
}

:deep(.wd-input__inner) {
  font-weight: bold;
  background: none !important;
}
</style>